package front_comment_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type CommentListReq struct {
	ArticleID uint `form:"article_id" json:"article_id" binding:"required"`
}

type CommentListRsp struct {
	ID              uint   `json:"id"`
	CreateAt        string `json:"create_at"`
	ParentCommentID *uint  `json:"parent_comment_id"` // 父评论id
	Content         string `json:"content"`           // 评论内容
	DiggCount       int    `json:"digg_count"`        // 点赞数
	CommentCount    int    `json:"comment_count"`     // 子评论数
	ArticleID       uint   `json:"article_id"`        // 文章id
	UserID          uint   `json:"user_id"`           // 评论用户id
	// 以下不是表结构
	SubComments []*CommentListRsp `json:"sub_comments"` // 子评论列表
	User        *UserRsp          `json:"user"`         // 关联的用户
}

type UserRsp struct {
	ID       uint   `json:"id"`
	NickName string `json:"nick_name"` // 昵称
	Avatar   string `json:"avatar"`    // 头像
}

func (CommentApi) CommentList(c *gin.Context) {
	var req CommentListReq
	if err := c.ShouldBindQuery(&req); err != nil {
		logrus.Error(err)
		panic(err)
	}
	// 查问文章的所有评论
	var commentListRspList []*CommentListRsp
	global.DB.Model(models.CommentModel{}).Where("article_id = ?", req.ArticleID).Find(&commentListRspList)
	// 获取根评论
	var baseCommentList []*CommentListRsp
	// ParentCommentID相同的评论
	commentMap := make(map[*uint][]*CommentListRsp)
	var userIdList []uint
	for _, model := range commentListRspList {
		if model.ParentCommentID == nil {
			baseCommentList = append(baseCommentList, model)
		}
		commentMap[model.ParentCommentID] = append(commentMap[model.ParentCommentID], model)
		userIdList = append(userIdList, model.UserID)
	}
	var userRspList []*UserRsp
	global.DB.Model(models.UserModel{}).Find(&userRspList, userIdList)
	userRspMap := make(map[uint]*UserRsp)
	for _, rsp := range userRspList {
		userRspMap[rsp.ID] = rsp
	}
	// 递归去装数据
	buildSubComment(baseCommentList, commentMap, userRspMap)
	res.OkWithDate(baseCommentList, c)
}

func buildSubComment(baseCommentList []*CommentListRsp, commentMap map[*uint][]*CommentListRsp, userRspMap map[uint]*UserRsp) {
	for _, rsp := range baseCommentList {
		sub := commentMap[&rsp.ID]
		if sub == nil {
			return
		}
		rsp.SubComments = sub
		rsp.User = userRspMap[rsp.UserID]
		buildSubComment(sub, commentMap, userRspMap)
	}
}
